package com.woniu.consumer.controller;

import com.woniu.consumer.entity.Product;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.yaml.snakeyaml.events.Event;

import java.io.IOException;

/**
 * @author SuperYu  2024/9/26
 */
@RestController
@RefreshScope
public class SendController {

    @Autowired
    RestTemplate restTemplate;

    @Value("${goods.count}")
    double count;

    @RequestMapping("/getMsg/{id}")
    public Product getMsg(@PathVariable int id) throws IOException {

        System.out.println("读取到配置中心的值："+count);

        String url = "http://localhost:8090/product/" + id;
        String url2 = "http://localhost:8091/product/" + id;
        String url3 = "http://localhost:8092/product/" + id;

        Product p = null;
        if (System.currentTimeMillis() % 3 == 0) {
            p = restTemplate.getForObject(url, Product.class);
        } else if(System.currentTimeMillis() % 3 == 1){
            p = restTemplate.getForObject(url2, Product.class);
        }else {
            p = restTemplate.getForObject(url3, Product.class);

        }
        System.out.println("得到的产品对象：" + p);
        return p;
    }

    @RequestMapping("/getProduct/{id}")
    public String getProduct(@PathVariable int id) throws IOException {

        String url = "http://localhost:8090/product/" + id;

        // 得到一个客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        // 发送一个get请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 得到内容
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");

        return result;
    }

    @RequestMapping("/getProductObject/{id}")
    public Product getProductObject(@PathVariable int id) throws IOException {
        String url = "http://localhost:8090/product/" + id;
        Product p = restTemplate.getForObject(url, Product.class);
        System.out.println("得到的产品对象：" + p);
        return p;
    }


}
